﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SpyApp.Models;
using SpyApp.Models.BaseCommon.ERROR_CODE;

namespace SpyApp.Controllers
{
    public class HomeController : Controller
    {
        string _messageError = "";
        public UserRepository userRepository { get; set; }

        public HomeController()
        {
            this.userRepository = new UserRepository();
        }

        public ActionResult Index(string deviceid)
        {
            string username = HttpContext.User.Identity.Name;
            // get, send MessageError, MessageSuccess
            ViewBag.MessageError = TempData["MessageError"];
            ViewBag.MessageSuccess = TempData["MessageSuccess"];
            Device device = new Device();
            // tìm thiết bị            
            ERROR_CODE_ITEMS_SELECT errCode = userRepository.GetDeviceByUserName(deviceid, username, ref _messageError, ref device);
            if (errCode != ERROR_CODE_ITEMS_SELECT.SUCCESS)
            {
                // none device => first device
                IEnumerable<Device> listDevice = new List<Device>();
                errCode = userRepository.GetListDeviceByUserName(username, ref _messageError, ref listDevice);
                if (errCode == ERROR_CODE_ITEMS_SELECT.SUCCESS && listDevice.Count() > 0)
                {
                    device = listDevice.First();
                }
                else
                {
                    // non device => message
                    return RedirectToAction("NoDevice", "Device");
                }
            }
            //NGhĩa: thông tin thiết bị
            return View(device);
        }

        [HttpPost]
        public ActionResult Login(string userName, string passWord)
        {
            UserRepository user = new UserRepository();
            var _user = user.Login(userName, passWord);
            if(_user != null)
                  ViewBag.Status = "CORRECT UserName and Password";            
            else            
                ViewBag.Status = "INCORRECT UserName or Password";
            return View(_user);
        }
    }
}
